package com.shanzmoo.admin.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanzmoo.admin.domain.bo.MallOrderContactsBO;
import com.shanzmoo.admin.domain.bo.MallOrderInvoiceBO;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.constant.MallOrderStatus;
import com.shanzmoo.core.cache.CurrentUserCache;
import com.shanzmoo.db.mall.entity.MallOrderDetailEntity;
import com.shanzmoo.db.mall.entity.MallOrderEntity;
import com.shanzmoo.db.mall.entity.bo.MallOrderAddLogisticsBO;
import com.shanzmoo.db.mall.entity.bo.MallOrderSellerRemarkBO;
import com.shanzmoo.db.mall.entity.query.MallOrderPageQuery;
import com.shanzmoo.db.mall.entity.vo.MallOrderDetailVO;
import com.shanzmoo.db.mall.entity.vo.MallOrderPageVO;
import com.shanzmoo.db.mall.service.IMallOrderDetailService;
import com.shanzmoo.db.mall.service.IMallOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 *
 * @author： Gzhao 2021/1/31
 */

@Slf4j
@Component
public class MallOrderManager {

    @Autowired
    private IMallOrderService mallOrderService;
    @Autowired
    private IMallOrderDetailService mallOrderDetailService;

    public SResponse<PageRespBase<MallOrderPageVO>> getPageList(MallOrderPageQuery query) {
        // 开启分页
        Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());

        List<MallOrderEntity> list = mallOrderService.list(
                new QueryWrapper<MallOrderEntity>()
                        .eq("deleted", false)
                        .eq(query.getStatus() != null, "status", query.getStatus())
                        .like(StrUtil.isNotBlank(query.getOrderNo()), "order_no", query.getOrderNo())
                        .like(StrUtil.isNotBlank(query.getUsername()), "username", query.getUsername())
                        .orderByAsc("status = 9")
                        .orderByDesc("create_time")
        );
        if (CollectionUtil.isEmpty(list)) {
            return SResponse.ok(PageRespBase.empty(query.getPageSize()));
        }

        List<MallOrderPageVO> reList = list.stream().map(MallOrderPageVO::create).collect(Collectors.toList());

        // 订单明细
        List<MallOrderDetailEntity> mallOrderDetailEntityList = mallOrderDetailService.list(
                new QueryWrapper<MallOrderDetailEntity>()
                        .eq("deleted", false)
                        .in("order_id", reList.stream().map(MallOrderPageVO::getId).collect(Collectors.toList()))
        );
        reList.forEach(e -> {
            List<MallOrderDetailVO> detailList = mallOrderDetailEntityList.stream()
                    .filter(detail -> detail.getOrderId().equals(e.getId()))
                    .map(MallOrderDetailVO::create)
                    .collect(Collectors.toList());
            e.setDetailList(detailList);
        });


        PageRespBase<MallOrderPageVO> re = PageRespBase.create(page, reList);
        PageHelper.clearPage();
        return SResponse.ok(re);
    }

    public SResponse<Boolean> addLogistics(MallOrderAddLogisticsBO logistics) {
        MallOrderEntity orderEntity = mallOrderService.getOne(
                new QueryWrapper<MallOrderEntity>()
                        .eq("order_no", logistics.getOrderNo())
                        .eq("status", MallOrderStatus.WAIT_SEND)
        );
        if (orderEntity == null){
            return SResponse.fail(Constant.ERRCODE_LOGIC, "请选择待发货订单");
        }

        orderEntity.setLogisticsNo(logistics.getLogisticsNo());
        orderEntity.setLogisticsType(logistics.getLogisticsType());
        orderEntity.setStatus(MallOrderStatus.ALREADY_SEND);
        orderEntity.setUpdateUser(CurrentUserCache.getUserId());
        mallOrderService.updateById(orderEntity);

        return SResponse.ok(Boolean.TRUE);
    }

    public SResponse<Boolean> addSellerRemark(MallOrderSellerRemarkBO sellerRemark) {
        MallOrderEntity orderEntity = mallOrderService.getOne(
                new QueryWrapper<MallOrderEntity>()
                        .eq("order_no", sellerRemark.getOrderNo())
        );
        if (orderEntity == null){
            return SResponse.fail(Constant.ERRCODE_LOGIC, "请输入正确订单号");
        }

        orderEntity.setSellerRemark(sellerRemark.getSellerRemark().trim());
        orderEntity.setUpdateUser(CurrentUserCache.getUserId());
        mallOrderService.updateById(orderEntity);

        return SResponse.ok(Boolean.TRUE);
    }

//    public List<ProductSalesVO> getProductSales() {
//        return mallOrderService.getProductSales();
//    }

    @Transactional(rollbackFor = Exception.class)
    public SResponse<Boolean> updateContacts(MallOrderContactsBO request) {
        MallOrderEntity orderEntity = mallOrderService.getById(request.getId());

        Assert.isTrue(ObjectUtil.isNotNull(orderEntity), "请输入正确订单号");
        Assert.isTrue(ObjectUtil.equals(orderEntity.getStatus(), MallOrderStatus.WAIT_PAY)
                        || ObjectUtil.equals(orderEntity.getStatus(), MallOrderStatus.WAIT_SEND)
                , "订单状态异常");

        orderEntity.setContacts(request.getContacts());
        orderEntity.setMobile(request.getMobile());
        orderEntity.setDistrictStr(request.getDistrictStr());
        orderEntity.setAddress(request.getAddress());
        orderEntity.setUpdateUser(CurrentUserCache.getUserId());
        mallOrderService.updateById(orderEntity);

        mallOrderService.saveOperateLog(orderEntity.getId(), "更新收货信息", CurrentUserCache.getUserId());
        return SResponse.ok(Boolean.TRUE);
    }

    @Transactional(rollbackFor = Exception.class)
    public SResponse<Boolean> updateInvoice(@org.jetbrains.annotations.NotNull MallOrderInvoiceBO request) {
        MallOrderEntity orderEntity = mallOrderService.getById(request.getId());

        Assert.isTrue(ObjectUtil.isNotNull(orderEntity), "请输入正确订单号");
        Assert.isTrue(ObjectUtil.equals(orderEntity.getStatus(), MallOrderStatus.WAIT_PAY)
                        || ObjectUtil.equals(orderEntity.getStatus(), MallOrderStatus.WAIT_SEND)
                , "订单状态异常");

        orderEntity.setInvoiceType(0);
        orderEntity.setInvoiceTitle(request.getInvoiceTitle());
        orderEntity.setInvoiceIdentification(request.getInvoiceIdentification());
        orderEntity.setInvoiceEmail(request.getInvoiceEmail());
        orderEntity.setInvoiceContentType(request.getInvoiceContentType());
        orderEntity.setUpdateUser(CurrentUserCache.getUserId());
        mallOrderService.updateById(orderEntity);

        mallOrderService.saveOperateLog(orderEntity.getId(), "更新发票信息", CurrentUserCache.getUserId());
        return SResponse.ok(Boolean.TRUE);
    }
}
